
import json
import urllib3
import xlrd
import math
import datetime
http = urllib3.PoolManager(num_pools=5, maxsize=10)

# ---Global---
investor_id = 'test_uesr_1'
server_url = "http://172.24.7.76:8081"
create_url = server_url + "/portfolio/create"
update_url = server_url + "/portfolio/update"
trade_url = server_url + "/trade"

INIT_CAPITAL = 1000000


def Auth(_investor_id):
    from datetime import datetime
    import hashlib

    # 待加密信息
    mark = 'portfolio'
    investor_id = str(_investor_id)
    dt = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    key = investor_id + '_' + dt + '_' + mark
    # 创建md5对象
    md5_hash = hashlib.md5()
    md5_hash.update(key.encode(encoding='utf-8'))

    # Tips
    # 此处必须声明encode
    # 若写法为hl.update(str) 报错为： Unicode-objects must be encoded before hashing

    # print('MD5加密前为 ：' + key)
    # print('MD5加密后为 ：' + md5_hash.hexdigest())
    result = {'investor_id' : investor_id, 'date' : dt, 'md5' : md5_hash.hexdigest()}
    return result


def CreatePortfolio(portfolioName, info="NA"):
    #
    url = create_url
    body = {}
    body["name"] = portfolioName
    body["info"] = info
    body["base_code"] = "000300.SH"
    body["init_amount"] = INIT_CAPITAL
    body["commission"] = 0
    body["status"] = 0
    body["group_id"] = "test_group"
    body['auth'] = Auth(investor_id)
    body['investor_id'] = investor_id

    #
    b = json.dumps(body)
    print(b)
    response = http.request('POST', url, body=json.dumps(body), timeout=1)
    print(url, response.status, response.data.decode('utf8'))
    portfolio_id = json.loads(response.data.decode('utf8'))['code_msg']['portfolio_id']
    pass


def UpdatePortfolio(portfolio_id,
                    updatePortfolioName=None,
                    updateInfo=None,
                    updateBenchmarkSymbol=None):

    body = {}
    body["portfolio_id"] = portfolio_id

    if updatePortfolioName:
        body["name"] = updatePortfolioName

    if updateInfo:
        body["info"] = updateInfo

    if updateBenchmarkSymbol:
        body["base_code"] = updateBenchmarkSymbol

    # body["commission"] = 0
    # body['status'] = 0

    # portfolio_id = json.loads(response.data.decode('utf8'))['code_msg']['portfolio_id']
    url = update_url
    body['portfolio_id'] = portfolio_id
    body['auth'] = Auth(investor_id)
    response = http.request('POST', url, body = json.dumps(body), timeout=1)
    print(url, response.status, response.data.decode('utf8'))


# symbol : 000001.SZ
# side: buy / sell
# qty: 100 / 500 / 1000
# price: 9.5
# tradeDatetime: "2018-09-14 22:41:50"
def AddTrade(portfolio_id, symbol, side, qty, price, tradeDateTime):

    body = {}

    body["portfolio_id"] = portfolio_id
    body["code"] = symbol
    body['volume'] = int(qty / 100.0) * 100
    body['price'] = price
    body['trade_time'] = ToDateTimeString(tradeDateTime)
    body['direction'] = side
    body['auth'] = Auth(investor_id)

    url = trade_url
    response = http.request('POST', url, body=json.dumps(body), timeout=1)
    print(url, response.status, response.data.decode('utf8'))


def ToDateTimeString(date):
    s = date.strftime('%Y-%m-%d %H:%M:%S')
    return s

def ReadExcelFile(excelPathfilename, sheetName = "Sheet1"):

    # ---Load Text File---
    book = xlrd.open_workbook(excelPathfilename)
    sheet = book.sheet_by_name(sheetName)

    nrows = sheet.nrows
    ncols = sheet.ncols
    i = 0;
    headerIndexByName = {}
    table = []
    for i in range(0, nrows):
        row_data = sheet.row_values(i)
        content = row_data
        if content[0] == "":
            continue

        # Process Headers
        if i == 0:
            headerCount = 0
            for header in content:
                headerIndexByName[header] = headerCount
                headerCount = headerCount + 1
            continue
        # Process Header Done

        #Process Contents
        entry = []
        for data in content:
            #data = data.strip("\n")
            entry.append(data)
        table.append(entry)

    return headerIndexByName, table


def ReadCSVFile(pathFilename,spliter = ","):
    file = open(pathFilename, 'r')
    i = 0
    headerIndexByName = {}
    table = []
    while True:
        s = file.readline()
        i = i+1
        if s == '':
            break

        content = s.split(spliter)
        #Process Headers
        if i == 1:
            headerCount = 0
            for header in content:
                header = header.strip(" ")
                header = header.strip("\n")
                headerIndexByName[header] = headerCount
                headerCount = headerCount + 1
            continue

        #Process Contents
        entry = []
        for data in content:
            data = data.strip("\n")
            entry.append(data)
        table.append(entry)

    return headerIndexByName,table


#####################################################################3
# ---开始---

# 建立组合
#CreatePortfolio("BigPlayer")
pass


# 存储组合名和ID的对照表
portdolioIDTable = {}
portdolioIDTable["KirklynTest"] = 188
portdolioIDTable["BigPlayer"] = 191
pass


# Use Excel To Trade
portdolioName = "BigPlayer"
# header, data = ReadExcelFile("D:\Data\PortfolioManagement\大股东增持.xlsx")
header, data = ReadExcelFile("D:\Data\PortfolioManagement\BigPlayer.xlsx")
for d in data:
    symbol = d[header["Symbol"]]
    qty = d[header["Qty"]]
    if qty > 0:
        side = "buy"
    elif qty < 0:
        side = "sell"
    else:
        continue

    price = float(d[header["Price"]])
    tradeDate = str(int(d[header["Date"]])) # wind "20180927"
    tradeTime = d[header["Time"]] # wind "11:29:59"
    strDateTime = tradeDate + " " + tradeTime
    tradeDateTime = datetime.datetime.strptime(strDateTime, "%Y%m%d %H:%M:%S")

    portfolioId = portdolioIDTable[portdolioName]
    AddTrade(portfolio_id=portfolioId,symbol=symbol,side=side,qty=math.fabs(qty),price=price,tradeDateTime=tradeDateTime)

pass